*************************************************************************************************************
*Table A.14: Heterogeneous effects of reconciliation on value disbursed and received by FPS balance
*This table reports differential effects of accumulated stock balance at the time of reconciliation onset (July 2017) on value disbursed by dealers and received by beneffciaries
*************************************************************************************************************


*****************************************************************************************************************
* Receipt
*****************************************************************************************************************

use "${SurveyDataDir}/JH_ePOS_HH_reconciliation_DataforAnalysis.dta",clear

rename admin_dealer_id_EL2 admin_dealer_id 


merge m:1 admin_dealer_id using "${AdminDataDir}/NICstock_cleaned_fpslevel.dta"	,gen(merge_stock) keep(1 3)   


merge m:1 admin_dealer_id using "${AdminDataDir}/dis_wheat_notzero_ind_fps.dta", nogen keep(1 3)



*recode missing wheat stock to be zero if the block kept getting zero disbursement for wheat, if not, keep as missing
replace stock_wheat=0 if missing(stock_wheat)& missing(dis_wheat_notzero_ind_fps)& merge_stock==3


*take out outliers in rice and wheat stock
 *if control, recode as missingg if stock > total disbursement from jan 17 (starts may in C)
 *if treatment, recode as missing if stock> total disbursement from jan 17 + 4* avg monthly from total since Jan17 (we are missing 4 months of disbursement for Trt)
 

foreach var in wheat rice{
 replace stock_`var'=. if ((stock_`var'> dis_qty_`var'_fromjan17) & treatment==0)
 gen dist_qty_`var'_monthly = dis_qty_`var'_fromjan17/6
 replace dis_qty_`var'_fromjan17 = dis_qty_`var'_fromjan17+ 4*dist_qty_`var'_monthly if treatment==1
 
 di in red "outlier adjust for `var
 replace stock_`var'=. if ((stock_`var'> dis_qty_`var'_fromjan17) & treatment==1)
 } 
 
 
*gen stock per RC per fps
merge m:1 admin_dealer_id using "${AdminDataDir}/allocation_fpslevel_jan17_nov17.dta",gen(RC_merge) keepusing(rc_count_jul17)
loc ration "rice wheat sugar salt kero"
foreach rat of local ration{
replace stock_`rat'=stock_`rat'/rc_count_jul17
}
*recode to missing rice and wheat stock if impossible - rice: 250 kg per RC, wheat: 150 kg per RC
*reasoning: assume HH size attached to dealer is 5 member HH and did not pick up any rice for 10 months, and as  PH HH in rural area they get 5 kg of rice - then 5*5*10
* assume same for wheat - one member can get 3 kg of wheat 
replace stock_rice=. if stock_rice>250
replace stock_wheat=. if stock_wheat>150
********************************
*Market price data for value estimates (from EL household survey)
********************************
preserve
use "${SurveyDataDir}/JH_ePOS_HH_DataforAnalysis.dta",clear
keep district_code d2_co_1_kirana_price_district d2_co_2_kirana_price_district d2_co_3_kirana_price_district d2_co_4_kirana_price_district d2_co_5_kirana_price_district stat_price_*
rename d2_co_1_kirana_price_district d2_rice_market_price_district
rename d2_co_2_kirana_price_district d2_wheat_market_price_district
rename d2_co_3_kirana_price_district d2_sugar_market_price_district
rename d2_co_4_kirana_price_district d2_salt_market_price_district
rename d2_co_5_kirana_price_district d2_kero_market_price_district
collapse d2* stat_price_*, by(district_code)
tostring district_code, replace format("%02.0f")
tempfile price_dat
save `price_dat', replace
restore
merge m:1 district_code using `price_dat', keep(3) nogen
*Generate stock value variables
*local month "jan17 feb17 mar17 apr17 may17 jun17 jul17 aug17 sep17 oct17 nov17"
local ration "rice wheat sugar salt kero"
foreach rat of local ration {
gen price_diff_`rat'= d2_`rat'_market_price_district - stat_price_`rat'_jul17
gen stock_`rat'_value =  (d2_`rat'_market_price_district - stat_price_`rat'_jul17)*stock_`rat'
}
*gen stock for total reconciled
gen stock_totalrec=stock_rice+stock_wheat
gen stock_totalrec_value=stock_rice_value+stock_wheat_value
***************************************************************
* Heterogeneity by balance for rice and wheat (all others do not have stock recorded beginning of July
***************************************************************
local ration_rec "totalrec rice wheat"
local rat "totalrec"
local month_list "nov17 oct17 sep17 aug17 jul17 jun17 may17 apr17 mar17 feb17 jan17"
scalar obs_all = 11*3960
foreach rat of local ration_rec {
preserve
keep dis_wheat_notzero_ind_fps  stock_`rat' stock_`rat'_value value_`rat'_*17 uid fps_uid index_* reconciliation_* post_reconciliation_* ghost_final pweight treatment strata block_code isurban signal_strength_med_1
local m = 11
foreach mon of local month_list{
rename value_`rat'_`mon' value_`rat'`m'
rename index_`mon' index`m' 
rename reconciliation_`mon' reconciliation`m'
rename post_reconciliation_`mon' post_reconciliation`m'
local m = `m' - 1
}
reshape long value_`rat' index reconciliation post_reconciliation, i(uid) j(month)
gen reconciliationXtmint = reconciliation*(index - 6)
rename stock_`rat'_value stock
di in red "	`rat' corr with stock "
*gen vars for balance interaction (stock each for commodity)
gen indexXstock = index*stock
gen recXstock=reconciliation*stock
gen rXtXs=reconciliationXtmint*stock
gen postrecXstock=post_reconciliation*stock
*gen vars for treatment interaction
gen indexXtrt = index*treatment
gen reconciliationXtrt=reconciliation*treatment
gen reconciliationXtmintXtrt=reconciliationXtmint*treatment
gen post_reconciliationXtrt=post_reconciliation*treatment
*gen strata and strata interaction effects manually (or regression would gen strata FE twice)
tab strata, gen(strata_)
 forvalues i=1/46{
 gen strataXstock`i'=strata_`i'*stock
 gen strataXtrt`i'=strata_`i'*treatment
 
 }
 
*have two groups of strata interactions: one for exogenous one for endogenous to be instrumented (some strata only have 2 blocks, thus their interac. with balance are perfectly predicted by strata*trt)
*list A is endogenous, list B is exogenous
*identify strata id corresponding to endogenous ones 
#delimit;
local stratalistA "1 2  3	 5	6	7	8 9 10	11	12 13 14 15	16	17	18	
                   19 20 21	22	23	24	25 26	27	28	29	30	31	32 33  36 38 39	
				   	40	41 42 43 44"  ;
#delimit cr
*identify strata id corresponding to exogenous ones 
local stratalistB "4 34 35 37 45 46"
local strataXstocklistA=" "
local strataXstocklistB=" "
local strataXtrtlistA=" "
local strataXtrtlistB=" "
*endogenous
foreach i of local stratalistA{
local strataXstocklistA "`strataXstocklistA' strataXstock`i' "
local strataXtrtlistA "`strataXtrtlistA' strataXtrt`i'"
}
di "`strataXstocklistA'"
di "`strataXtrtlistA'"
*exogenous
foreach i of local stratalistB{
local strataXstocklistB "`strataXstocklistB' strataXstock`i' "
local strataXtrtlistB "`strataXtrtlistB' strataXtrt`i'"
}
di "`strataXstocklistB'"
di "`strataXtrtlistB'"

********************************************************************************************************************
svyset [pw=pweight]
qui svy: mean value_`rat' if month == 1
qui estat sd
matrix Mean0 = r(mean)
set matsize 10000
set emptycells drop 
*stock balance interaction - main
#delimit;
eststo `rat'_hetero_stock_r: ivreg2 value_`rat' index reconciliation reconciliationXtmint post_reconciliation strata_* `strataXtrtlistA' `strataXstocklistB' treatment
(indexXstock recXstock rXtXs postrecXstock	
  = 																													
 indexXtrt reconciliationXtrt reconciliationXtmintXtrt post_reconciliationXtrt) 								
[pw = pweight], first cluster(fps_uid) savefirst savefprefix(`rat'fst_r);
#delimit cr
estadd scalar january_mean = `=Mean0[1,1]'
estadd scalar percent_obs 100*e(N)/obs_all

* Get the SW f-stats (SWF)
matrix swf    = e(first)
matrix min_swf = swf[8,1..4]
mata: a = min(st_matrix("min_swf"))
mata: b = st_local("b", strofreal(a))
estadd scalar min_swf = `b'

* Get the first-stage F-stat
matrix firsts    = e(first)
matrix min_first = firsts[4,1..4]
mata: x = min(st_matrix("min_first"))
mata: y = st_local("y", strofreal(x))
estadd scalar min_first = `y'

loc models "indexXstock recXstock rXtXs postrecXstock"

loc i = 0
local model "indexXstock"
foreach model of local models{

	loc i = `i' + 1

	est restore `rat'fst_r`model'
	eststo `rat'fst_r`model'
	sum `model' if month == 1
	estadd scalar fs_j_m = r(mean)
	estadd scalar fs_percent_obs = 100*e(N)/obs_all
	
	matrix xx = firsts[4,`i']
	mata: xx2 = st_matrix("xx")
	mata: yy = st_local("yy", strofreal(xx2))
	estadd scalar fs_first = `yy'

}

restore
}



*****************************************************************************************************************
* Disbursement
*****************************************************************************************************************
use "${AdminDataDir}/allocation_FPSlevel_jan17_nov17.dta",clear
merge 1:1 admin_dealer_id using "${AdminDataDir}/NICstock_cleaned_fpslevel.dta",nogen
merge 1:1 admin_dealer_id using "${AdminDataDir}/dis_wheat_notzero_ind_fps.dta", nogen
*recode missing wheat disbursement 
replace stock_wheat=0 if missing(stock_wheat)& missing(dis_wheat_notzero_ind_fps)    //recode wheat stock zero if missing and had been getting zero disbursement jan - jun 2017
*take out outliers in rice and wheat stock
 *if control, recode as missingg if stock > total disbursement from jan 17 (starts may in C)
 *if treatment, recode as missing if stock> total disbursement from jan 17 + 4* avg monthly from total since Jan17 (we are missing 4 months of disbursement for Trt)
 
foreach var in rice wheat{
  *control
 replace stock_`var'=. if ((stock_`var'> dis_qty_`var'_fromjan17) & treatment==0)
 
  *treatment
 gen dist_qty_`var'_monthly = dis_qty_`var'_fromjan17/6
 replace dis_qty_`var'_fromjan17 = dis_qty_`var'_fromjan17+ 4*dist_qty_`var'_monthly if treatment==1  //conjecture total disbursement since Aug'16
 replace stock_`var'=. if ((stock_`var'> dis_qty_`var'_fromjan17) & treatment==1)
 }
 
 /*
*get rc counts
merge m:1 admin_dealer_id using "`EL23disbursementDat'/20180529_allocation_fpslevel_jan17_nov17.dta",gen(RC_merge) keepusing(rc_count_jul17)
*/
*get stock per ration card 
loc ration "rice wheat sugar salt kero"
foreach rat of local ration{
replace stock_`rat'=stock_`rat'/rc_count_jul17
}
*recode to missing rice and wheat stock if impossible - rice: 250 kg per RC, wheat: 150 kg per RC
*reasoning: assume HH size attached to dealer is 5 member HH and did not pick up any rice for 10 months, and as  PH HH in rural area they get 5 kg of rice - then 5*5*10
* assume same for wheat - one member can get 3 kg of wheat 
replace stock_rice=. if stock_rice>250
replace stock_wheat=. if stock_wheat>150
*gen stock value 
local ration "rice wheat sugar salt kero"
foreach rat of local ration {
gen price_diff_`rat'= d2_`rat'_market_price_district - stat_price_`rat'_jul17
gen stock_`rat'_value =  (d2_`rat'_market_price_district - stat_price_`rat'_jul17)*stock_`rat'
}
*gen stock for total reconciled
gen stock_totalr=stock_rice+stock_wheat
gen stock_totalr_value=stock_rice_value+stock_wheat_value
replace dis_value_perRC_totalr_jul17=. if dis_value_perRC_totalr_jul17<0
replace dis_value_perRC_rice_jul17=. if dis_value_perRC_rice_jul17<0
*****************************************
* Heterogeniety by balanec for totalr wheat and rice 
*****************************************
local ration_rec "totalr rice wheat"
scalar obs_all = 9265*11
foreach rat of local ration_rec {
preserve
keep stock* dis_wheat_notzero_ind_fps dis_value_perRC_`rat'_*17 admin_dealer_id index_* reconciliation_* post_reconciliation_* rc_count* block_code isurban treatment strata
local m = 11
foreach mon of local month_list{
rename dis_value_perRC_`rat'_`mon' dis_value_perRC_`rat'`m'
rename index_`mon' index`m' 
rename reconciliation_`mon' reconciliation`m'
rename post_reconciliation_`mon' post_reconciliation`m'
rename rc_count_`mon' rc_count`m'
local m = `m' - 1
}
rename stock_`rat'_value stock
reshape long dis_value_perRC_`rat' index reconciliation post_reconciliation rc_count, i(admin_dealer_id) j(month)
gen reconciliationXtmint = reconciliation*(index - 6)
*gen vars for treatment interaction
gen indexXtrt = index*treatment
gen reconciliationXtrt=reconciliation*treatment
gen reconciliationXtmintXtrt=reconciliationXtmint*treatment
gen post_reconciliationXtrt=post_reconciliation*treatment
*gen vars for balance interaction (stock each for commodity)
gen indexXstock = index*stock
gen recXstock=reconciliation*stock
gen rXtXs=reconciliationXtmint*stock
gen postrecXstock=post_reconciliation*stock
*gen strata and strata interaction effects manually (or regression would gen strata FE twice)
tab strata, gen(strata_)
 forvalues i=1/46{
 gen strataXstock`i'=strata_`i'*stock
 gen strataXtrt`i'=strata_`i'*treatment
 
 }
 
 
*have two groups of strata interactions: one for exogenous one for endogenous to be instrumented (some strata only have 2 blocks, thus their interac. with balance are perfectly predicted by strata*trt)
*list A is endogenous, list B is exogenous
*identify strata id corresponding to endogenous ones 
#delimit;
local stratalistA "2  3	 5	6	7	10	11	14	15	16	17	18	
                   19 21	22	23	24	26	27	28	29	30	31	32	33	34	
				   35  37	40	42	43	46"  ;
#delimit cr
*identify strata id corresponding to exogenous ones 
local stratalistB "4 13	20	25	41	44	45 8 9 12 36 38 39"
local strataXstocklistA=" "
local strataXstocklistB=" "
local strataXtrtlistA=" "
local strataXtrtlistB=" "
*endogenous
foreach i of local stratalistA{
local strataXstocklistA "`strataXstocklistA' strataXstock`i' "
local strataXtrtlistA "`strataXtrtlistA' strataXtrt`i'"
}
di "`strataXstocklistA'"
di "`strataXtrtlistA'"
*exogenous
foreach i of local stratalistB{
local strataXstocklistB "`strataXstocklistB' strataXstock`i' "
local strataXtrtlistB "`strataXtrtlistB' strataXtrt`i'"
}
di "`strataXstocklistB'"
di "`strataXtrtlistB'"
 
qui: summarize dis_value_perRC_`rat' if month == 1 [aw=rc_count]
matrix Mean0 = r(mean)
*stock balance interaction - Main
#delimit;
eststo `rat'_hetero_stock_d:ivreg2 dis_value_perRC_`rat' index reconciliation reconciliationXtmint post_reconciliation strata_* `strataXtrtlistA' `strataXstocklistB' treatment
(indexXstock recXstock rXtXs postrecXstock
  = 
 indexXtrt reconciliationXtrt reconciliationXtmintXtrt post_reconciliationXtrt)
[aweight=rc_count], first cluster(admin_dealer_id) savefirst savefprefix(`rat'fst_d);
#delimit cr 
estadd scalar january_mean = `=Mean0[1,1]'
estadd scalar percent_obs 100*e(N)/obs_all

* Get the SW f-stats (SWF)
matrix swf    = e(first)
matrix min_swf = swf[8,1..4]
mata: a = min(st_matrix("min_swf"))
mata: b = st_local("b", strofreal(a))
estadd scalar min_swf = `b'

* Get the first-stage F-stat
matrix firsts    = e(first)
matrix min_first = firsts[4,1..4]
mata: x = min(st_matrix("min_first"))
mata: y = st_local("y", strofreal(x))
estadd scalar min_first = `y'

loc models "indexXstock recXstock rXtXs postrecXstock"

loc i = 0
foreach model of local models{

	loc i = `i' + 1

	est restore `rat'fst_d`model'
	eststo `rat'fst_d`model'
	sum `model' if month == 1
	estadd scalar fs_j_m = r(mean)
	estadd scalar fs_percent_obs = 100*e(N)/obs_all
	
	matrix xx = firsts[4,`i']
	mata: xx2 = st_matrix("xx")
	mata: yy = st_local("yy", strofreal(xx2))
	estadd scalar fs_first = `yy'
	
}

restore
}

* Table 8
# delimit;
esttab totalr_hetero_stock_d rice_hetero_stock_d wheat_hetero_stock_d totalrec_hetero_stock_r rice_hetero_stock_r wheat_hetero_stock_r using "${OutputDir}/Table8.tex" , 
	label b(%12.2g) se(%12.2g) booktabs replace nocons nolz 
	drop(_cons *strata* /*stock*/ index indexXstock treatment post_reconciliation postrecXstock)  width(\hsize)
    order ( reconciliation recXstock reconciliationXtmint rXtXs  )
	coeflabels( reconciliation "Reconciliation" recXstock "Reconciliation*Balance" reconciliationXtmint "Reconciliation*Month" rXtXs "Reconciliation*Month*Balance" )		
	   stats(january_mean N percent_obs min_first min_swf, 
			labels("January 2017 mean" "Observations" "\% of frame/sample" "Min. F-stat" "Min. S-W F-stat" 
				) fmt(%12.2g 0 0 0 0))
	star(* .10 ** .05 *** .01) 
	mgroups("Value disbursed" "Value received",	
			pattern(1 0 0 1 0 0 ) prefix(\multicolumn{@span}{c}{) suffix(}) 
			span erepeat(\cmidrule(lr){@span}))
	mlabel("Total" "Rice" "Wheat" "Total" "Rice" "Wheat")
	substitute("Standard errors in parentheses" " "
				"\sym{*} \(p<.10\), \sym{**} \(p<.05\), \sym{***} \(p<.01\)" " "
				"\multicolumn{6}{l}{\footnotesize  }\\" "");
				
#delimit cr 


* Table A.18 - total received/ disbursed
# delimit;
esttab 	
	totalrfst_dindexXstock totalrfst_drecXstock totalrfst_drXtXs totalrfst_dpostrecXstock
	totalrecfst_rindexXstock totalrecfst_rrecXstock totalrecfst_rrXtXs totalrecfst_rpostrecXstock
	using "${OutputDir}/TableA_18.tex" , 
	label b(%12.2g) se(%12.2g) booktabs replace nocons nolz 
	drop(_cons *strata* index post_reconciliation treatment reconciliation reconciliationXtmint)  width(\hsize)
    order (indexXtrt reconciliationXtrt reconciliationXtmintXtrt post_reconciliationXtrt)
	coeflabels( indexXtrt "Treatment*Month" reconciliationXtrt "Reconciliation*Treatment"  
				reconciliationXtmintXtrt "Reconciliation*Month*Treatment"
				post_reconciliationXtrt "Post-Reconciliation*Treatment") 		
	   stats(fs_j_m N fs_percent_obs fs_first, 
			labels("January 2017 mean" "Observations" "\% of frame/sample" "First-stage F-statistic") 
			fmt(%12.2g 0 0 %12.2f))
	star(* .10 ** .05 *** .01) 
	mgroups("Value disbursed" "Value received",	
			pattern(1 0 0 0 1 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) 
			span erepeat(\cmidrule(lr){@span}))
	mlabel(	"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}"
			"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}") 
	substitute("Standard errors in parentheses" " "
				"\sym{*} \(p<.10\), \sym{**} \(p<.05\), \sym{***} \(p<.01\)" " "
				"\multicolumn{6}{l}{\footnotesize  }\\" "");
				
#delimit cr 

* Rice received/ disbursed
# delimit;
esttab 	
	ricefst_dindexXstock ricefst_drecXstock ricefst_drXtXs ricefst_dpostrecXstock
	ricefst_rindexXstock ricefst_rrecXstock ricefst_rrXtXs ricefst_rpostrecXstock
	using "${OutputDir}/TableA_19.tex" , 
	label b(%12.2g) se(%12.2g) booktabs replace nocons nolz 
	drop(_cons *strata* index post_reconciliation treatment reconciliation reconciliationXtmint)  width(\hsize)
    order (indexXtrt reconciliationXtrt reconciliationXtmintXtrt post_reconciliationXtrt)
	coeflabels( indexXtrt "Treatment*Month" reconciliationXtrt "Reconciliation*Treatment"  
				reconciliationXtmintXtrt "Reconciliation*Month*Treatment"
				post_reconciliationXtrt "Post-Reconciliation*Treatment") 		
	   stats(fs_j_m N fs_percent_obs fs_first, 
			labels("January 2017 mean" "Observations" "\% of frame/sample" "First-stage F-statistic") 
			fmt(%12.2g 0 0 %12.2f))
	star(* .10 ** .05 *** .01) 
	mgroups("Value disbursed" "Value received",	
			pattern(1 0 0 0 1 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) 
			span erepeat(\cmidrule(lr){@span}))
	mlabel(	"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}"
			"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}") 
	substitute("Standard errors in parentheses" " "
				"\sym{*} \(p<.10\), \sym{**} \(p<.05\), \sym{***} \(p<.01\)" " "
				"\multicolumn{6}{l}{\footnotesize  }\\" "");
				
#delimit cr 

* Wheat received/ disbursed
# delimit;
esttab 	
	wheatfst_dindexXstock wheatfst_drecXstock wheatfst_drXtXs wheatfst_dpostrecXstock
	wheatfst_rindexXstock wheatfst_rrecXstock wheatfst_rrXtXs wheatfst_rpostrecXstock
	using "${OutputDir}/TableA_20.tex" , 
	label b(%12.2g) se(%12.2g) booktabs replace nocons nolz 
	drop(_cons *strata* index post_reconciliation treatment reconciliation reconciliationXtmint)  width(\hsize)
    order (indexXtrt reconciliationXtrt reconciliationXtmintXtrt post_reconciliationXtrt)
	coeflabels( indexXtrt "Treatment*Month" reconciliationXtrt "Reconciliation*Treatment"  
				reconciliationXtmintXtrt "Reconciliation*Month*Treatment"
				post_reconciliationXtrt "Post-Reconciliation*Treatment") 		
	   stats(fs_j_m N fs_percent_obs fs_first, 
			labels("January 2017 mean" "Observations" "\% of frame/sample" "First-stage F-statistic") 
			fmt(%12.2g 0 0 %12.2f))
	star(* .10 ** .05 *** .01) 
	mgroups("Value disbursed" "Value received",	
			pattern(1 0 0 0 1 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(}) 
			span erepeat(\cmidrule(lr){@span}))
	mlabel(	"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}"
			"Month*Stock" "\specialCellCenter{Reconciliation*\\Stock}" "\specialCellCenter{Rec*Month*\\Stock}" "\specialCellCenter{Post-Rec*\\Stock}") 
	substitute("Standard errors in parentheses" " "
				"\sym{*} \(p<.10\), \sym{**} \(p<.05\), \sym{***} \(p<.01\)" " "
				"\multicolumn{6}{l}{\footnotesize  }\\" "");
				
#delimit cr 



eststo clear
